package com.baoyouqun.controller.union;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.StrUtil;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baoyouqun.entity.City;
import com.baoyouqun.entity.User;
import com.baoyouqun.service.CityService;
import com.baoyouqun.service.UserService;
import io.swagger.annotations.ApiOperation;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.StringUtil;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@SaIgnore
@RestController
@RequestMapping("/city")
public class CityController {

    @Resource
    private CityService cityService;
    @Resource
    @Lazy
    private UserService userService;

    @ApiOperation("地区选择树状列表")
    @GetMapping(value = "/tree")
    public Response tree() {
        return SingleResponse.of(cityService.getTree());
    }


    @ApiOperation("地区选择树状列表_带用户数")
    @GetMapping(value = "/treeUserCount")
    public Response treeUserCount() {
        return SingleResponse.of(cityService.treeUserCount());
    }

    @ApiOperation("地区选择树状列表_带发帖数")
    @GetMapping(value = "/treeDemandCount")
    public Response treeDemandCount() {
        return SingleResponse.of(cityService.treeDemandCount());
    }

    /**
     * 同步用户的cityCode字段（根据district匹配城市数据）
     */
    @PostMapping("/cityCode")
    @Transactional(rollbackFor = Exception.class)
    public void syncUserCityCode() {
        List<String> failReasons = new ArrayList<>();

        // 1. 预加载所有城市数据（内存映射：key=城市名称，value=城市对象）
        List<City> allCities = cityService.list();
        Map<String, City> cityNameMap = allCities.stream()
                .collect(Collectors.toMap(
                        city -> city.getName().trim(),  // 城市名称去空格，避免匹配误差
                        city -> city,
                        (existing, replacement) -> existing  // 名称重复时保留第一个
                ));

        // 2. 查询需要同步的用户（可根据业务调整条件，这里示例：非注销用户）
        List<User> users = userService.list(
                new LambdaQueryWrapper<User>()
                        .select(
                                User::getId,
                                User::getDistrict,
                                User::getCityCode  // 只查询需要的字段，减少数据传输
                        )
        );

        // 3. 遍历用户，同步cityCode
        for (User user : users) {
            String userId = user.getId();
            String district = StringUtil.isNotBlank(user.getDistrict()) ? user.getDistrict().trim() : "";
            if (StringUtil.isBlank(user.getDistrict()) && StringUtil.isBlank(user.getCityCode())) {
                continue;
            }


            try {
                // 3.1 若district为空，跳过处理
                if (StrUtil.isBlank(district)) {
                    continue;
                }

                // 3.2 根据district匹配城市数据中的名称
                City matchedCity = cityNameMap.get(district);
                if (matchedCity == null) {
                    // 匹配失败：记录原因
                    failReasons.add("用户ID: " + userId + "，区县名称「" + district + "」在城市数据中不存在");
                    continue;
                }

                // 3.3 若cityCode已正确，无需更新
                String targetCityCode = matchedCity.getCode();
                if (StrUtil.equals(user.getCityCode(), targetCityCode)) {
                    continue;
                }

                // 3.4 更新用户的cityCode
                user.setCityCode(targetCityCode);
                userService.updateById(user);  // 只更新变化的字段（mybatis-plus默认动态SQL）

            } catch (Exception e) {
                // 处理异常：记录原因
                failReasons.add("用户ID: " + userId + "，处理异常-" + e.getMessage());
            }
        }
    }
}
